import React, { useState } from 'react';
import { Upload, Button, message, Card, Typography } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

const { Text } = Typography;

function OCRUpload() {
  const [result, setResult] = useState('');

  const handleUpload = async ({ file }) => {
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('/ocr/', {
        method: 'POST',
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        if (data.text) {
          setResult(data.text);
          message.success('OCR 完成！');
        } else {
          message.error(data.error || '未检测到文字');
        }
      } else {
        message.error('服务器错误: ' + response.statusText);
      }
    } catch (error) {
      message.error('请求失败: ' + error.message);
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <Card title="OCR 图片识别"  style={{ width: 300 }}>
        <Upload
          name="image"
           accept="image/*,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf"
          customRequest={handleUpload}
          showUploadList={false}
        >
          <Button icon={<UploadOutlined />}>上传图片</Button>
        </Upload>
        {result && (
          <div style={{ marginTop: '20px' }}>
            <Text strong>识别结果：</Text>
            <Text style={{ whiteSpace: 'pre-wrap' }}>{result}</Text>
          </div>
        )}
      </Card>
    </div>
  );
}

export default OCRUpload;